"""条码处理模型"""
from app.database import get_db_connection

def generate_check_digit(barcode):
    """计算EAN-13条码的校验码"""
    digits = list(barcode)
    sum = 0
    for i in range(12):
        digit = int(digits[i])
        if i % 2 == 0:
            sum += digit
        else:
            sum += digit * 3
    
    check_digit = (10 - (sum % 10)) % 10
    return str(check_digit)

def convert_to_ean13():
    """将数据库中的现有条码转换为EAN-13标准"""
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        cursor.execute("SELECT barcode FROM products")
        products = cursor.fetchall()
        
        for product in products:
            old_barcode = product['barcode']
            cleaned_barcode = ''.join(filter(str.isdigit, str(old_barcode)))
            
            if not cleaned_barcode:
                print(f"跳过无效条码: {old_barcode}")
                continue
            
            if len(cleaned_barcode) == 13:
                try:
                    check_digit = generate_check_digit(cleaned_barcode[:12])
                    if check_digit == cleaned_barcode[12]:
                        if cleaned_barcode != old_barcode:
                            cursor.execute(
                                "UPDATE products SET barcode = %s WHERE barcode = %s",
                                (cleaned_barcode, old_barcode)
                            )
                        continue
                except Exception as e:
                    print(f"验证条码 {cleaned_barcode} 时出错: {e}")
            
            prefix = "690"
            padded_barcode = (cleaned_barcode + "0000000000")[:9]
            new_barcode_part = prefix + padded_barcode[:9]
            check_digit = generate_check_digit(new_barcode_part)
            new_barcode = new_barcode_part + check_digit
            
            cursor.execute(
                "UPDATE products SET barcode = %s WHERE barcode = %s",
                (new_barcode, old_barcode)
            )
            print(f"已将条码 {old_barcode} 转换为 {new_barcode}")
        
        connection.commit()
        print("所有商品条码已转换为EAN-13标准")
    except Exception as e:
        if connection:
            connection.rollback()
        print(f"转换条码时出错: {e}")
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

